import re

class Traj(object):
    def __init__(self, num):
        self._traj = [[] for _ in range(num)]
        self._traj_num = num

    def getTraj(self):
        return self._traj
        
    def getNum(self):
        return self._traj_num

    def append(self, i, t):
        self._traj[i].append(t)
        #print 'append {0}'.format(i)
        #print self._traj[i]

    def save(self, file_name='traj.txt'):
        f = open(file_name, 'w')
        for i in range(self._traj_num):
            #print '{0}'.format(self._traj[i])
            for j in range(0, len(self._traj[i]), 3):
                f.write('({0:.2f}, {1:.2f}, {2:.2f}) '.format(self._traj[i][j], self._traj[i][j+1], self._traj[i][j+2]))
            f.write('\n')
        f.close()

    def load(self, file_name='traj.txt'):
        self._traj = []
        try:
            f = open(file_name)
        except IOError:
            print('file open error')
        else:
            while True:
                line = f.readline()
                if not line:
                    break

                line = line.strip()
                m = re.findall('[-+]?\d*\.\d+|\d+', line)
                if m is not None:
                    self._traj.append([])
                    self._traj[-1] = [float(m[j]) for j in range(len(m))]
            self._traj_num = len(self._traj)
        finally:
            f.close()
        return self._traj, self._traj_num
